<?php

/**
 * 文章控制器
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-05
 */

namespace app\admin\controller;

use app\admin\model\Art;
use app\common\logic\Response;
use fw\base\Conf;
use fw\base\View;
use fw\tool\Json;
use fw\tool\Request;
use fw\tool\Session;

class ControllerArt extends Base
{
    public function add()
    {
        if (Request::isPost()) {
            $_POST['manager_id'] = Session::gi()->get('auth.manager_id');
            $ret = Art::gi()->add();

            echo Json::encode($ret);
        } else {
            View::render('art_add');
        }
    }

    public function update()
    {
        if (Request::isPost()) {
            $_POST['manager_id'] = Session::gi()->get('auth.manager_id');
            $ret = Art::gi()->update();
            $ret['code'] == 200 && $ret['code'] = 0;

            echo Json::encode($ret);
        } else {
            $art_id = Request::get('art_id');
            $data = Art::gi()->getInfo(['art_id' => $art_id]);

            // 输出到视图
            View::render('art_update', ['data' => $data,]);
        }
    }

    public function browse()
    {
        // 参数获取
        $length = Conf::$all['page_length'];
        $current_page = (int)Request::get('page', null, 1);

        // 条数总计
        $list_count = Art::gi()->getList([
            'is_count' => true,
        ]);
        $page_total = ceil($list_count / $length);

        // 分页
        $option = [
            'current_page' => $current_page,
            'page_total'   => $page_total,
            'list_count'   => $list_count,
        ];
        $page = new \app\common\logic\Page($option);
        $page_show = $page->show();

        // 查询列表
        $data = Art::gi()->getList([
            'length' => $length,
            'page'   => $current_page,
        ]);

        // 输出到视图
        View::render('art_browse', ['page_show' => $page_show, 'data' => $data]);
    }

    public function del()
    {
        if (Request::isPost()) {
            $art_ids = isset($_POST['ids']) ? explode(',', $_POST['ids']) : [];

            $resp = Response::to();
            foreach ($art_ids as $art_id) {
                $manager_id = Session::gi()->get('auth.manager_id');
                $resp = Art::gi()->del(['art_id' => $art_id, 'op_user' => $manager_id]);
                if ($resp['code'] != 0) break;
            }

            echo Json::encode($resp);
        } else {
            $art_ids = Request::get('ids');
            if (empty($art_ids)) {
                View::error(['msg' => 'Require art_id.']);
            }

            $data = Art::gi()->getList(['art_ids' => $art_ids]);

            // 输出到视图
            View::render('art_del', ['data' => $data]);
        }
    }
}
